<template>
	<div id="cate_right">
		<div class="category_right">
			<div class="category_detail">
				<h3 class="category_n">{{CategoryName}}</h3>
				<ul class="overflow_hidden">
					<li class="category_detail_item" v-for="item in mainDatas">
						<router-link :to="'/detail/'+item.Id" class="category_detail_item_link">
							<img v-lazy="root + item.ImgPath" alt="" class="category_detail_item_pic">
							<p class="category_detail_item_name">{{item.ProductName}}</p>
						</router-link>
					</li>
				</ul>
			</div>
			<infinite-loading :on-infinite="onInfinite" ref="infiniteLoading">
				<span slot="no-more">
    								没有更多商品了 :(
  								</span>
  								<span slot="no-results">
	    								没有更多商品了 :(
	  								</span>
			</infinite-loading>
		</div>
	</div>
</template>
<script>
	import InfiniteLoading from 'vue-infinite-loading';

	export default {
		mounted() {
			var reg = /category\/\d+/;
			let path = this.$route.path
			if(path == '/category') {
				this.getData()
			} else {
				this.categotyId = path.split('/')[2]
				console.log('this.categotyId', this.categotyId)
				this.fetchData(this.categotyId, this.currentPage);
			}
		},
		data() {
			return {
				mainDatas: [],
				categotyId: 0,
				currentPage: 1,
				CategoryName: '热门商品',

			}
		},
		watch: {
			$route(to) {
				console.log('to', to);
				var reg = /category\/\d+/;
				if(reg.test(to.path)) {
					this.categotyId = this.$route.params.id || 0;
					this.currentPage = 1;
					this.mainDatas = [];
					this.fetchData(this.categotyId, this.currentPage);
				}
			}
		},
		methods: {
			onInfinite() {
				setTimeout(() => {
					this.currentPage++
						this.fetchData(this.categotyId, this.currentPage);
				}, 1000);
			},
			fetchData(id, page) {
				var _this = this;
				console.log('id', id)
				_this.$http.get('/Client/Products?OnSale=1&limit=18&page=' + page, {
					CategoryId: id
				}, localStorage.Authorization, res => {
					console.log('右边商品res', res)
					if(res.code === 200) {
						if(res.data.list.length>0) {
							_this.mainDatas = _this.mainDatas.concat(res.data.list);
							_this.CategoryName = _this.mainDatas[0].CategoryName;
							_this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
							if(res.data.list.length == 0) {
								_this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete');
							}
						}else {
							_this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete');
						}
					}
				})
			},
			getData() {
				let _this = this;
				_this.$http.get('/Client/Products?OnSale=1&limit=18', null, localStorage.Authorization, res => {
					console.log('商品列表res', res)
					if(res.code === 101) {

					} else {
						_this.mainDatas = []
						_this.mainDatas = res.data.list;
						_this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete');
						
					}
				})
			}
		},
		components: {
			InfiniteLoading,
		},
	}
</script>